package cn.copera.dyy.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.copera.dyy.common.test.ImageUtil;
import cn.copera.dyy.common.utils.FileUtils;
import cn.copera.dyy.common.utils.StringUtils;
import cn.copera.dyy.common.web.BaseController;
import cn.copera.dyy.entity.Shop;
import cn.copera.dyy.entity.ShopImage;
import cn.copera.dyy.service.ShopImageService;
import cn.copera.dyy.service.ShopService;

/**
 * 上传图片Controller
 *
 */
@Controller
@RequestMapping(value = "${adminPath}/uploadfile")
public class UploadfileController extends BaseController {
	
	@Autowired
	private ShopImageService shopImageService;
	@Autowired
	ShopService shopService;
	
	
	

	@SuppressWarnings("unused")
	@RequestMapping(value = "upload")
	public void upload(HttpServletRequest request, PrintWriter out) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		MultipartFile multipartFile = null;
		SimpleDateFormat format = new SimpleDateFormat("yyyy/M/d");
		String shopId = request.getParameter("shopId");   //文件所属业务模块
		Shop shop = shopService.get(shopId);
		String path = "/images/";
		String realPath = request.getSession().getServletContext().getRealPath(path);
		String type =  request.getParameter("type");
		String id = request.getParameter("id");
		FileUtils.createDirectory(realPath);
		ShopImage shopImage = null;
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
		String filename = sf.format(new Date())+".jpg";
		for (Map.Entry<String, MultipartFile> set : fileMap.entrySet()) {
			multipartFile = set.getValue();  // 文件
			if(type!=null&&type.equals("headImage")){
				shop.setHeadImage(path+filename);
				shopService.save(shop);
			}else{
				if("shop_img".equals(request.getParameter("flag"))){
					shopImageService.deleteImage(shopId);
				}
				if(id==null||id.equals("")||id.equals("null")){
					shopImage = new ShopImage();
				}else{
					shopImage=shopImageService.getShopImage(id);
				}
			
				shopImage.setShop(shop);
				shopImage.setType(type);
				shopImage.setDescription(request.getParameter("description"));
				shopImage.setFlag(request.getParameter("flag"));
				
				shopImage.setFileName(path+filename);
				shopImage.setName(multipartFile.getOriginalFilename());
				shopImageService.save(shopImage);
			}
			
			if(multipartFile != null && multipartFile.getSize() > 0){
				FileOutputStream fs;
				try {
					fs = new FileOutputStream(realPath + "/"+ filename);
			        byte[] buffer =new byte[1024*1024];
			        int bytesum = 0;
			        int byteread = 0;
			        InputStream stream = multipartFile.getInputStream();
			        while ((byteread=stream.read(buffer))!=-1)
			        {
			           bytesum+=byteread;
			           fs.write(buffer,0,byteread);
			           fs.flush();
			        } 
			        fs.close();
			        stream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(shopImage!=null&&shopImage.getFlag()!=null&&StringUtils.isNotBlank(shopImage.getFlag())&&(shopImage.getFlag().equals("set")||shopImage.getFlag().equals("shop_img"))){
				File f = new File(realPath + "/"+ filename);
				
				
				
				FileInputStream fis;
				try {
					fis = new FileInputStream(f);
					BufferedImage bufferedImg = ImageIO.read(fis);
					int imgWidth = bufferedImg.getWidth();
					if(imgWidth>480){
						ImageUtil.resize(f, f, 480, 1f);
					}
					float scale=1f;
					long size = f.length()/1024;
					while(size>100){
						scale-=0.1f;
						ImageUtil.resize(f, f, 480, scale);
						size = f.length()/1024;
					}
					
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
		}
		
	}
}
